package com.xiaorun.portal.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiaorun.portal.constant.WebConst;
import com.xiaorun.portal.dao.CarouselMapper;
import com.xiaorun.portal.dao.EnterpriseMapper;
import com.xiaorun.portal.modal.Bo.Query;
import com.xiaorun.portal.modal.Vo.Carousel;
import com.xiaorun.portal.modal.Vo.Enterprise;
import com.xiaorun.portal.service.ICarouselService;
import com.xiaorun.portal.service.IEnterpriseService;
import com.xiaorun.portal.utils.QiNiuImgUpload;
import com.xiaorun.portal.utils.TaleUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import javax.xml.bind.DatatypeConverter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by BlueT on 2018/3/3.
 */
@Service
@Slf4j
public class CarouselServiceImpl implements ICarouselService {

    @Autowired
    private CarouselMapper carouselMapper;

    @Autowired
    private QiNiuImgUpload qiNiuImgUpload;

    @Override
    public int countTotal(Map<String, Object> params) {
        Query query = new Query(params != null ? params: new HashMap<>());
        int num = carouselMapper.countTotal(query);
        return num;
    }

    @Override
    public List<Carousel> list(Map<String, Object> params) {
        Query query = new Query(params != null ? params: new HashMap<>());
        List<Carousel> carousels = carouselMapper.list(query);
        return carousels;
    }

    @Override
    public PageInfo<Carousel> list(int pageNum, int pageSize, Map<String, Object> params) {
        PageHelper.startPage(pageNum, pageSize);
        Query query = new Query(params != null ? params: new HashMap<>());
        List<Carousel> carousels = carouselMapper.list(query);
        PageInfo<Carousel> pageInfo = new PageInfo(carousels);
        return pageInfo;
    }

    @Override
    public int save(Carousel carousel){

        String img = carousel.getImg();
        if(img.startsWith("data:image/")){
            String[] imgArr = img.split(",");
            img = imgArr[1];
            byte[] b =DatatypeConverter.parseBase64Binary(img);
            img = qiNiuImgUpload.uploadImg(b);
            carousel.setImg(img);
        }
        int result;
        if(carousel.getId() != null){
            result = carouselMapper.update(carousel);
        }else{
            result = carouselMapper.save(carousel);
        }
        return result;
    }

    @Override
    public Carousel get(int id) {
        return carouselMapper.get(id);
    }

    @Override
    public int remove(int id) {
        return carouselMapper.remove(id);
    }

}
